package com.stadium.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.stadium.common.BaseResponse;
import com.stadium.common.exception.RRException;
import com.stadium.common.utils.*;
import com.stadium.dto.*;
import com.stadium.entity.*;
import com.stadium.mapper.GamePlayerMP;
import com.stadium.mapper.GameTeamMP;
import com.stadium.mapper.RTeamUserMP;
import com.stadium.mapper.SysUserMP;
import com.stadium.service.FaceRegSV;
import com.stadium.service.GamePlayerSV;
import com.stadium.service.SysUserVerifaceSV;
import com.stadium.vo.*;
import com.stadium.vo.searchVo.GamePlayerSearchVo;
import com.stadium.vo.searchVo.GameScheduleSearchVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class GamePlayerSVI implements GamePlayerSV {
    @Autowired
    private GamePlayerMP mapper;
    @Autowired
    private SqlMapper sqlMapper;
    @Autowired
    private SysUserMP sysUserMP;
    @Autowired
    private RTeamUserMP rTeamUserMP;
    @Autowired
    private FaceRegSV faceRegSV;
    @Autowired
    private SysUserVerifaceSV sysUserVerifaceSV;
    @Autowired
    private GameTeamMP gameTeamMP;

    /**
     * 上传文件的路径配置
     */
    @Value("${upload-file.uploadFileUrl}")
    private String uploadFileUrl;
    @Value("${upload-file.FileUrl}")
    private String FileUrl;
    @Value("${upload-file.uploadFileSymbol}")
    private String uploadFileSymbol;


    @Override
    public List<GamePlayer> queryBySQL(String sql, Map<String, Object> map) {
        return sqlMapper.selectList(sql, map, GamePlayer.class);
    }

    @Override
    public void save(GamePlayerVo gamePlayerVo) {

        SysUserDto sysUserDto =sysUserMP.getUserByIdNumber(gamePlayerVo.getIdNumber());
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(gamePlayerVo,sysUser);
        GamePlayer gamePlayer = new GamePlayer();
        BeanUtils.copyProperties(gamePlayerVo, gamePlayer);
        if(sysUserDto == null){
            String userId = UUID.randomUUID().toString().replaceAll("-", "");
            sysUser.setId(userId);
            sysUser.setPassword(Md5Utils.hash("000000"));
            sysUser.setRole("1");
            sysUser.setIsAdmin("0");
            sysUser.setCreateUser(UserUtils.getUserId());
            sysUser.setUpdateUser(UserUtils.getUserId());
            sysUserMP.save(sysUser);
            gamePlayer.setUserId(userId);
        }else {
            sysUser.setId(sysUserDto.getId());
            sysUserMP.update(sysUser);
            gamePlayer.setUserId(sysUserDto.getId());
        }
        if(gamePlayerVo.getHeadPortrait() != null){
            CreatFaceDto creatFaceDto = faceRegSV.fileUrlConvertDface(uploadFileUrl + gamePlayerVo.getHeadPortrait());
            if (creatFaceDto.isResult()) {
                SysUserVerifaceDto sysUserVerifaceDto = sysUserVerifaceSV.getByUserId(sysUser.getId());
                String md5 = Md5Utils.hash(creatFaceDto.getFaceFeatureBase64());
                if (sysUserVerifaceDto != null) {
                    if (!sysUserVerifaceDto.getFileMd5().equals(md5)) {
                        SysUserVerifaceVo sysUserVerifaceVo = new SysUserVerifaceVo();
                        BeanUtils.copyProperties(sysUserVerifaceDto, sysUserVerifaceVo);
                        sysUserVerifaceVo.setUserId(sysUser.getId());
                        sysUserVerifaceVo.setFileMd5(md5);
                        sysUserVerifaceVo.setContent(creatFaceDto.getFaceFeatureBase64());
                        sysUserVerifaceSV.update(sysUserVerifaceVo);
                    }
                } else {
                    SysUserVerifaceVo sysUserVerifaceDb = new SysUserVerifaceVo();
                    sysUserVerifaceDb.setUserId(sysUser.getId());
                    sysUserVerifaceDb.setFileMd5(md5);
                    sysUserVerifaceDb.setContent(creatFaceDto.getFaceFeatureBase64());
                    sysUserVerifaceSV.save(sysUserVerifaceDb);
                }
            } else {
                throw new RRException("该照片不符合人脸导入！");
            }
        }
        GamePlayerDto gamePlayerDto = mapper.getByUserId(gamePlayer.getUserId());
        if (gamePlayerDto == null) {
            String playerid = UUID.randomUUID().toString().replaceAll("-", "");
            gamePlayer.setId(playerid);
            gamePlayer.setCreateUser(UserUtils.getUserId());
            gamePlayer.setUpdateUser(UserUtils.getUserId());
            mapper.save(gamePlayer);

        }else {
            gamePlayer.setId(gamePlayerDto.getId());
            mapper.update(gamePlayer);
        }
    }

    public void importSave(GamePlayerVo gamePlayerVo,String teamId) {
        SysUserDto sysUserDto =sysUserMP.getUserByIdNumber(gamePlayerVo.getIdNumber());
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(gamePlayerVo,sysUser);
        GamePlayer gamePlayer = new GamePlayer();
        BeanUtils.copyProperties(gamePlayerVo, gamePlayer);
        if(sysUserDto == null){
            String userId = UUID.randomUUID().toString().replaceAll("-", "");
            sysUser.setId(userId);
            sysUser.setPassword(Md5Utils.hash("000000"));
            sysUser.setRole("1");
            sysUser.setIsAdmin("0");
            sysUser.setCreateUser(UserUtils.getUserId());
            sysUser.setUpdateUser(UserUtils.getUserId());
            sysUserMP.save(sysUser);
            gamePlayer.setUserId(userId);
        }else {
            sysUser.setId(sysUserDto.getId());
            sysUserMP.update(sysUser);
            gamePlayer.setUserId(sysUserDto.getId());
        }
        GamePlayerDto gamePlayerDto = mapper.getByUserId(gamePlayer.getUserId());
        if (gamePlayerDto == null) {
            String playerid = UUID.randomUUID().toString().replaceAll("-", "");
            gamePlayer.setId(playerid);
            gamePlayer.setCreateUser(UserUtils.getUserId());
            gamePlayer.setUpdateUser(UserUtils.getUserId());
            mapper.save(gamePlayer);
        }else {
            gamePlayer.setId(gamePlayerDto.getId());
            mapper.update(gamePlayer);
        }
        RTeamUser rTeamUser1 = rTeamUserMP.getbyTeamIdAndUserId(teamId, gamePlayer.getUserId());
        if (rTeamUser1 == null) {
            RTeamUser rTeamUser = new RTeamUser();
            String id = UUID.randomUUID().toString().replaceAll("-", "");
            rTeamUser.setId(id);
            rTeamUser.setUserId(gamePlayer.getUserId());
            rTeamUser.setTeamId(teamId);
            rTeamUser.setAuditStatus("1");
            rTeamUserMP.save(rTeamUser);
        }
    }

    @Override
    public void update(GamePlayerVo gamePlayerVo) {
        GamePlayerDto gamePlayerDto = mapper.get(gamePlayerVo.getId());
        if(gamePlayerDto.getUserId() == null){
            throw new RRException("该用户不存在");
        }
        SysUser sysUser = new SysUser();
        sysUser.setId(gamePlayerDto.getUserId());
        if(StringUtils.isNotEmpty(gamePlayerVo.getName())){
            sysUser.setName(gamePlayerVo.getName());
        }
        if(StringUtils.isNotEmpty(gamePlayerVo.getPhoneNum())){
            sysUser.setPhoneNum(gamePlayerVo.getPhoneNum());
        }
        if(StringUtils.isNotEmpty(gamePlayerVo.getHeadPortrait())){
            sysUser.setHeadPortrait(gamePlayerVo.getHeadPortrait());
        }
        if(StringUtils.isNotEmpty(gamePlayerVo.getIdNumber())){
            sysUser.setIdNumber(gamePlayerVo.getIdNumber());
        }
        sysUserMP.update(sysUser);
        if(gamePlayerVo.getHeadPortrait() != null){
            CreatFaceDto creatFaceDto = faceRegSV.fileUrlConvertDface(uploadFileUrl + gamePlayerVo.getHeadPortrait());
            if (creatFaceDto.isResult()) {
                SysUserVerifaceDto sysUserVerifaceDto = sysUserVerifaceSV.getByUserId(sysUser.getId());
                String md5 = Md5Utils.hash(creatFaceDto.getFaceFeatureBase64());
                if (sysUserVerifaceDto != null) {
                    if (!sysUserVerifaceDto.getFileMd5().equals(md5)) {
                        SysUserVerifaceVo sysUserVerifaceVo = new SysUserVerifaceVo();
                        BeanUtils.copyProperties(sysUserVerifaceDto, sysUserVerifaceVo);
                        sysUserVerifaceVo.setUserId(sysUser.getId());
                        sysUserVerifaceVo.setFileMd5(md5);
                        sysUserVerifaceVo.setContent(creatFaceDto.getFaceFeatureBase64());
                        sysUserVerifaceSV.update(sysUserVerifaceVo);
                    }
                } else {
                    SysUserVerifaceVo sysUserVerifaceDb = new SysUserVerifaceVo();
                    sysUserVerifaceDb.setUserId(sysUser.getId());
                    sysUserVerifaceDb.setFileMd5(md5);
                    sysUserVerifaceDb.setContent(creatFaceDto.getFaceFeatureBase64());
                    sysUserVerifaceSV.save(sysUserVerifaceDb);
                }
            } else {
                throw new RRException("该照片不符合人脸导入！");
            }
        }
        GamePlayer gamePlayer = new GamePlayer();
        BeanUtils.copyProperties(gamePlayerVo, gamePlayer);
        gamePlayer.setUpdateUser(UserUtils.getUserId());
        mapper.update(gamePlayer);
    }

    @Override
    public void saveBatch(List<GamePlayer> list) {
        mapper.saveBatch(list);
    }

    @Override
    public void delete(String id) {
        GamePlayerDto gamePlayerDto = mapper.get(id);
        mapper.delete(id);
        sysUserMP.delete(gamePlayerDto.getUserId());
        int a =rTeamUserMP.getbyUserId(gamePlayerDto.getUserId());
        if (a > 0) {
            rTeamUserMP.deleteByUserId(gamePlayerDto.getUserId());
        }
    }

    @Override
    public void deleteBatch(String[] ids) {
        mapper.deleteBatch(ids);
    }

    @Override
    public List<GamePlayerDto> query(GamePlayerSearchVo searchVo) {
        return mapper.query(searchVo);
    }

    @Override
    public GamePlayerDto get(String id) {
        return mapper.get(id);
    }

    @Override
    public int getCount(GamePlayerSearchVo searchVo) {
        return mapper.getCount(searchVo);
    }

    @Override
    @Transactional
    public BaseResponse importUserToTeam(ImportUserVo importUserVo) {
        if (!importUserVo.getMultipartFile().isEmpty()) {
            String suffix = importUserVo.getMultipartFile().getOriginalFilename().substring(importUserVo.getMultipartFile().getOriginalFilename().lastIndexOf("."));
            try {
                List<GamePlayerVo> gamePlayerVoList = ExcelToObj.excelToUser(suffix,importUserVo.getMultipartFile().getInputStream());

                for (GamePlayerVo gamePlayerVo : gamePlayerVoList) {
                    this.importSave(gamePlayerVo,importUserVo.getTeamId());
                }
            } catch (IOException e) {
                e.printStackTrace();
                return BaseResponse.error("数据有误");

            }

        }
        return BaseResponse.ok();
    }

    @Override
    public GamePlayerDto getByUserId(String id) {
        return mapper.getByUserId(id);
    }

    @Override
    public ImportPhotoDto importPhoto(ImportPhotoVo importPhotoVo) throws Exception {
        ImportPhotoDto importPhotoDto = new ImportPhotoDto();
        List<ImportPhotoDetailsDto> importPhotoDetailsDtoList = new ArrayList<>();
        importPhotoDto.setImportPhotoDetailsDtoList(importPhotoDetailsDtoList);
        Integer errorTotal = 0;
        importPhotoDto.setErrorTotal(errorTotal);
        importPhotoDto.setSuccessTotal(0);
        importPhotoDto.setNoFindTotal(0);
        FileDto fileDto = FileUtils.uploadFile(importPhotoVo.getMultipartFile(), "zip");
        File file = new File(fileDto.getFileStoragePath());
        //解压基础地址
        String baseZipPath = uploadFileUrl + FileUrl + uploadFileSymbol + "zip";
        //本次解压文件地址
        String upZippath = baseZipPath + uploadFileSymbol + UUID.randomUUID().toString();
        ZipUtils.unZip(file, upZippath);
        //删除压缩包
        FileUtils.deleteFile(file);
        //本次解压出来的图片临时存放地址
        File unFile = new File(upZippath);
        List<File> newFiles = new ArrayList<>();
        //获取全部的解压文件
        List<File> fileList = FileUtils.func(unFile, newFiles);
        //查询全部运动员
        GamePlayerSearchVo basicsPlayerSearchVo = new GamePlayerSearchVo();
        basicsPlayerSearchVo.setTeamId(importPhotoVo.getTeamId());
        List<GamePlayerDto> treeviewUserDtoList = mapper.queryPlayerAndDface(basicsPlayerSearchVo);
        //文件存放地址
        String onceBaseFilePath = uploadFileUrl + FileUrl + uploadFileSymbol + "playerPhoto";
        //图片相对路径地址
        String onceBasePath = FileUrl + uploadFileSymbol + "playerPhoto" + uploadFileSymbol;
        String contrast = "";
        //需要更新的用户列表
        List<SysUser> needToUpdatePlayerList = new ArrayList<>();
        List<SysUserVeriface> sysUserVerifaceArrayList = new ArrayList<>();
        for (File oneFile : fileList) {
            String oneFileName = oneFile.getName();
            String frontName = oneFileName.substring(0, oneFileName.lastIndexOf("."));
            String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + oneFileName.substring(oneFileName.lastIndexOf(".") - 1, oneFileName.length());
            for (GamePlayerDto basicsPlayerDto : treeviewUserDtoList) {
                InputStream in = new FileInputStream(oneFile);
                // 命名类型 0:身份证号；1手机号码
                if (importPhotoVo.getNameType().equals("0")) {
                    contrast = basicsPlayerDto.getIdNumber();
                } else if (importPhotoVo.getNameType().equals("1")) {
                    contrast = basicsPlayerDto.getPhoneNum();
                }
                if (contrast.equals(frontName)) {

                    CreatFaceDto creatFaceDto = new CreatFaceDto();
                    SysUser basicsPlayer = new SysUser();
                    creatFaceDto = faceRegSV.fileUrlConvertDface(oneFile.getPath());
                    if (creatFaceDto.isResult()) {
                        String md5 = "";
                        if (creatFaceDto.getFaceFeatureBase64() != null) {
                            md5 = Md5Utils.hash(creatFaceDto.getFaceFeatureBase64());
                        }
                        if (basicsPlayerDto.getFileMd5() == null || !basicsPlayerDto.getFileMd5().equals(md5)) {
                            FileUtils.copyFile(oneFile.getPath(), onceBaseFilePath + "/" + newFileName);
                            SysUserVeriface sysUserVeriface = new SysUserVeriface();
                            basicsPlayer.setId(basicsPlayerDto.getUserId());
                            String oneFilePath = onceBasePath + newFileName;
                            basicsPlayer.setHeadPortrait(oneFilePath);
                            needToUpdatePlayerList.add(basicsPlayer);
                            sysUserVeriface.setUserId(basicsPlayerDto.getUserId());
                            sysUserVeriface.setContent(String.valueOf(creatFaceDto.getFaceFeatureBase64()));
                            sysUserVeriface.setFileMd5(md5);
                            sysUserVerifaceArrayList.add(sysUserVeriface);
                        }
                    } else {
                        errorTotal++;
                        ImportPhotoDetailsDto importPhotoDetailsDto = new ImportPhotoDetailsDto();
                        importPhotoDetailsDto.setErrCode((Integer) creatFaceDto.getErrCode());
                        importPhotoDetailsDto.setName(basicsPlayerDto.getName());
                        importPhotoDetailsDto.setIdNo(basicsPlayerDto.getIdNumber());
                        importPhotoDetailsDto.setPhoneNum(basicsPlayerDto.getPhoneNum());
                        importPhotoDetailsDto.setErrMsg(String.valueOf(creatFaceDto.getErrMsg()));
                        importPhotoDetailsDtoList.add(importPhotoDetailsDto);
                    }

                    //删除原来头像
                    if (basicsPlayerDto.getHeadPortrait() != null) {
                        FileUtils.delFile(basicsPlayerDto.getHeadPortrait());
                    }

                }
                in.close();
            }
        }
        if (needToUpdatePlayerList.size() > 0) {
            importPhotoDto.setSuccessTotal(needToUpdatePlayerList.size());
            importPhotoDto.setNoFindTotal(fileList.size() - needToUpdatePlayerList.size());
            List<SysUser> PlayerList = new ArrayList<>();
            for (int i = 0; i < needToUpdatePlayerList.size(); i++) {
                PlayerList.add(needToUpdatePlayerList.get(i));
                if ((i % 100 == 0 & i != 0) || i == needToUpdatePlayerList.size() - 1) {
                    sysUserMP.updateBatch(PlayerList);
                    PlayerList.clear();
                }
            }
        }
        for (SysUserVeriface sysUserVeriface : sysUserVerifaceArrayList) {
            SysUserVerifaceDto sysUserVerifaceDb = sysUserVerifaceSV.getByUserId(sysUserVeriface.getUserId());
            SysUserVerifaceVo sysUserVerifaceVo = new SysUserVerifaceVo();
            BeanUtils.copyProperties(sysUserVeriface, sysUserVerifaceVo);
            if (sysUserVerifaceDb != null) {
                sysUserVerifaceSV.update(sysUserVerifaceVo);
            } else {
                sysUserVerifaceSV.save(sysUserVerifaceVo);
            }
        }
        return importPhotoDto;
    }

    @Override
    public void updatePlayer(GamePlayerVo gamePlayerVo) {
        GamePlayer gamePlayer = new GamePlayer();
        BeanUtils.copyProperties(gamePlayerVo,gamePlayer);
        mapper.update(gamePlayer);
    }

    @Override
    public TeamRecord palyerRecorg(String userId) {
        TeamRecord teamRecord = gameTeamMP.palyerRecorg(userId);
        GameScheduleSearchVo gameScheduleSearchVo = new GameScheduleSearchVo();
        return teamRecord;
    }

    @Override
    public List<GamePlayerDto> queryPlayerAndDface(GamePlayerSearchVo searchVo) {
        return mapper.queryPlayerAndDface(searchVo);
    }

    @Override
    public int getPlayerCount(GamePlayerSearchVo searchVo) {
        return mapper.getPlayerCount(searchVo);
    }

}
